package com.cm367.teamc;

import java.sql.SQLException;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;

import com.cm367.teamc.bean.User;
import com.cm367.teamc.service.UserService;
import com.cm367.teamc.session.UserSession;

@ManagedBean
public class MainLogin {

	@ManagedProperty(value = "#{userService}")
	private UserService userService;

	@ManagedProperty(value = "#{userSession}")
	private UserSession userSession;

	private String userID;
	private String password;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserSession getUserSession() {
		return userSession;
	}

	public void setUserSession(UserSession userSession) {
		this.userSession = userSession;
	}

	public String getUserID() {
		return userID;
	}

	public void setUserID(String userID) {
		this.userID = userID.toLowerCase();
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String validateLogin() {
		User user = null;
		try {
			user = userService.findUser(userID, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (user != null) {
			userSession.setUserID(userID);
			userSession.setRole(user.getRole());
			userSession.setUserName(user.getUserName());
			userSession.setDepartment(user.getDepartment());
		} else {
			return "eLeaveLogin";
		}
		if (userSession.getRole().equals("admin")) {
			return "adminHome";
		} else if (userSession.getRole().equals("Manager")) {
			return "managerHome";
		} else {
			return "userHome";
		}
	}

	public String logout() {
		userSession.setUserID(null);
		userSession.setRole(null);
		userSession.setUserName(null);
		userSession.setDepartment(null);
		return "index";
	}
}
